package com.learn.english.controller;

import com.learn.english.domain.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

/**
 * @author TISNIW
 * @version 1.0
 * @date 2025/6/21 22:32
 * @desc
 */
@RestController
@RequestMapping("/file")
public class FileController {
    @Value("${path.user.file_url}")
    private String filePath;
    @GetMapping("/get/image")
    public ResponseEntity<InputStreamResource> getImage(@RequestParam String url) throws IOException {
        // 构建完整路径，防止路径穿越攻击
        Path imagePath = Paths.get(filePath, url).normalize();

        // 确保访问路径不超出配置目录范围
        if (!imagePath.startsWith(filePath)) {
            throw new SecurityException("非法路径访问");
        }

        // 检查文件是否存在，若不存在使用默认头像
        if (!Files.exists(imagePath)) {
            throw new IOException("文件不存在");
        }

        // 获取输入流
        InputStreamResource resource = new InputStreamResource(Files.newInputStream(imagePath));

        // 自动识别 MIME 类型（如 image/png）
        MediaType mediaType = MediaType.parseMediaType(Files.probeContentType(imagePath));

        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_TYPE, mediaType.toString())
                .body(resource);
    }
}
